<?php
/**
 * Created by PhpStorm.
 * User: YAN
 * Date: 2017/7/26
 * Time: 9:38
 */

namespace App\Http\Controllers\API;


use App\Http\Controllers\Controller;
use App\Models\EnglishResults;
use App\Models\ExamResults;
use App\Models\Student;
use App\Models\StudentEp;
use App\Models\StudentLog;
use Illuminate\Http\Request;

class StudentEnglishController extends Controller
{
    public function index(Request $request)
    {
        $id = $request->get('id', '');
        $open_id = $request->get('open_id', '');
        $s_id = $request->get('year','');
        try{
            if(empty($id)&&empty($open_id)){
                throw new \Exception('缺少Open-Id');
            }
            $CET4 = [];
            $CET6 = [];
            $student = Student::query()->orwhere('id',$id)->orWhere('wx_key',$open_id)->first();
            if(!$student){
                throw new \Exception('未找到该名学生');
            }
            $query= EnglishResults::with(['Semesters'])->where(['s_id'=>$student->id]);
            if($s_id){
                $query->where(['semester_id'=>$s_id]);
            }
            $exams = $query->orderBy('time')->get();
            if($exams){
                foreach ($exams as $items){
                    $item['time'] = date('Y-m-d', $items->time);
                    $item['e_number'] = $items->e_number;
                    $item['semester_name'] = $items->semesters->s_name;
                    $item['e_name'] = $items->e_name;
                    $item['serial_number'] = $items->serial_number;
                    $item['credit'] = $items->credit;
                    $item['e_codes'] = $items->e_codes;
                    $item['e_jd_codes'] = $items->e_jd_codes;
                    $item['s_name'] = $student->u_name;
                    $item['s_code'] = $student->u_code;
                    $item['ticket'] = $items->ticket;
                    if($items->e_name == "CET-4"){
                        $CET4[] = $item;
                    }else{
                        $CET6[] = $item;
                    }

                }
            }
            $result[0]['name'] = "CET-4";
            $result[0]['data'] = $CET4;
            $result[1]['name'] = "CET-6";
            $result[1]['data'] = $CET6;
            $log = new StudentLog();
            $log->student_id = $student->id;
            $log->logs = '通过微信端查看了英语等级考试成绩';
            if(!$log->save()){
                throw new \Exception('记录添加失败');
            }
            return $result;
        }catch (\Exception $e){
            return response($e->getMessage(), 406);
        }

    }
}